import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://localhost:8081/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    console.log('Axios 响应拦截器收到数据：', res)
    
    // 处理后端返回的数据格式 { code: 200, data: xxx, message: 'xxx' }
    if (res.code !== 200) {
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    return res  // 返回完整的响应数据，包含 code、data 和 message
  },
  error => {
    console.error('Axios 响应拦截器错误：', error)
    if (error.response) {
      const { status, data } = error.response
      if (status === 401) {
        ElMessage.error(data.message || '登录已过期，请重新登录')
        localStorage.removeItem('token')
        router.push('/login')
      } else if (status === 403) {
        ElMessage.error(data.message || '没有权限访问')
      } else if (status === 400) {
        ElMessage.error(data.message || '请求参数错误')
      } else if (status === 500) {
        ElMessage.error(data.message || '服务器内部错误')
      } else {
        ElMessage.error(data.message || '请求失败')
      }
    } else if (error.message.includes('timeout')) {
      ElMessage.error('请求超时，请稍后重试')
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
    return Promise.reject(error)
  }
)

export default request 